Vue 自定义组件的 v-model
v-model 是 Vue2 中唯一支持双向绑定的指令,其实是个语法糖
- v-model 使用
<input v-model="value" />
- 以上 input 的 v-model 使用其实是以下示例的语法糖
<input v-bind:value="value" v-on:input="value = $event.target.value" />
<!-- 简写: -->
<input :value="value" @input="value = $event.target.value" />
以一个 search 组件为例
search 组件相关代码
<template>
<div>
<input @input="onKeyInput" :value="value" />
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: "",
},
},
watch: {
keyword(nVal) {
this.$emit("input", nVal);
this.$emit("change", nVal);
},
value: {
immediate: true,
handler(nVal) {
this.keyword = nVal;
},
},
},
data() {
return {
keyword: "",
};
},
methods: {
onKeyInput(event) {
this.keyword = event.target.value;
},
},
};
</script>
- 页面引用
<template>
<div>
<m-search v-model="inputValue"></m-search>
</div>
</template>
<script>
export default {
data() {
return {
inputValue: "", //该值随着子组件 keyword 变量的内容改变而改变
};
},
};
</script>
Powered by Waline v2.15.8